package com.sky.api.sys.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.api.sys.param.request.InsertSysUserModel;
import com.sky.api.sys.param.request.PageQuerySysUser;
import com.sky.base.annotation.LogOperation;
import com.sky.model.OperateModelById;
import com.sky.api.sys.param.request.UpdateSysUserModel;
import com.sky.api.sys.param.response.SysUserModel;
import com.sky.base.constant.DataStatus;
import com.sky.base.controller.BaseController;
import com.sky.model.SysUser;
import com.sky.service.ISysUserService;
import com.sky.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * @author 尹稳健~
 * @version 1.0
 * @time 2022/9/1
 */
@RestController
@RequestMapping("/manage/sys/user")
@Api(tags = "系统管理-系统用户管理")
@Slf4j
public class SysUserController extends BaseController {

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 添加系统用户
     * @param insertSysUserModel
     * @return
     */
    @LogOperation("添加系统用户操作")
    @PostMapping("/insertSysUser")
    @ApiOperation("添加系统用户")
    public R<String> insertSysUser(@RequestBody @Valid InsertSysUserModel insertSysUserModel){
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(insertSysUserModel,sysUser);
        // 添加用户默认等级是 1，不是管理员权限
        sysUser.setHierarchy((short) 1);
        sysUser.setStatus(DataStatus.NORMAL);
        sysUser.setCreateId(getUserId());
        sysUser.setUpdateId(getUserId());
        sysUser.setCreateTime(LocalDateTime.now());
        sysUser.setUpdateTime(LocalDateTime.now());
        // 保存密码使用bCryptPasswordEncoder加密
        sysUser.setPassword(bCryptPasswordEncoder.encode(insertSysUserModel.getPassword()));
        Assert.isTrue(iSysUserService.save(sysUser),"添加失败");
        return R.ok();
    }

    /**
     * 根据id软删除系统用户
     * @param operaModelById
     * @return
     */
    @DeleteMapping("/deleteSysUser")
    @ApiOperation("软删除系统用户")
    @LogOperation("软删除系统用户")
    public R<String> deleteSysUser(@RequestBody @Valid OperateModelById operaModelById){
        iSysUserService.deleteSysUser(operaModelById.getId(),getUserId());
        return R.ok();
    }

    /**
     * 修改系统用户信息
     * @param updateSysUserModel  修改系统用户信息入参模型
     * @return
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    @PostMapping("updateSysUser")
    @ApiOperation("修改系统用户信息")
    @LogOperation("修改系统用户信息")
    public R<String> updateSysUser(@RequestBody @Valid UpdateSysUserModel updateSysUserModel) throws IllegalAccessException, InstantiationException {
        // 创建对象尽量不要使用new关键字
        Class<SysUser> sysUserClass = SysUser.class;
        SysUser sysUser = sysUserClass.newInstance();
        BeanUtils.copyProperties(updateSysUserModel,sysUser);
        // 将前端传入的密码进行加密
        sysUser.setPassword(bCryptPasswordEncoder.encode(updateSysUserModel.getPassword()));
        iSysUserService.updateSysUser(sysUser,getUserId());
        return R.ok();
    }

    /**
     * 根据id查询单个系统用户
     * @param operateModelById
     * @return
     */
    @PostMapping("/queryById")
    @ApiOperation("根据id查询系统用户")
    public R<SysUserModel> queryById(@RequestBody @Valid OperateModelById operateModelById) {
        SysUser sysUser = iSysUserService.queryById(operateModelById.getId());
        Class<SysUserModel> sysUserModelClass = SysUserModel.class;
        SysUserModel sysUserModel = null;
        try {
            sysUserModel = sysUserModelClass.newInstance();
        } catch (Exception e) {
            log.info("创建SysUserModel报错");
            e.printStackTrace();
        }
        BeanUtils.copyProperties(sysUser,sysUserModel);
        return R.ok(sysUserModel);
    }

    @ApiOperation("分页查询系统用户")
    @PostMapping("/pageQuery")
    public R<IPage<SysUserModel>> pageQuery(@RequestBody @Valid PageQuerySysUser pageQuerySysUser){
        IPage<SysUser> iPage = iSysUserService.pageQuery(pageQuerySysUser);
        IPage<SysUserModel> page = new Page<>();
        BeanUtils.copyProperties(iPage,page,"records");
        List<SysUserModel> records = iPage.getRecords().stream()
                .map(sysUser -> {
                    SysUserModel sysUserModel = new SysUserModel();
                    BeanUtils.copyProperties(sysUser, sysUserModel);
                    return sysUserModel;
                })
                .collect(Collectors.toList());
        page.setRecords(records);
        return R.ok(page);
    }


}
